import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Tag, Button, Space, message } from 'antd';
import { UserOutlined, DollarOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const ContractPayment = () => {
  const actionRef = useRef();
  const [summaryData, setSummaryData] = useState({
    totalCustomers: 0,
    totalReceivableAmount: 0,
  });

  // 列状态管理 - 控制哪些列默认隐藏
  const [columnsStateMap, setColumnsStateMap] = useState({
    salesperson: {
      show: false, // 接单人默认隐藏
    },
    lastPushTime: {
      show: false, // 上次推送时间默认隐藏
    },
    assistant: {
      show: false, // 协助人默认隐藏
    },
  });

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // Mock 数据
  const mockData = [
    {
      id: 1,
      customerCode: 'KH001',
      serviceProject: '代理记账+报税',
      customerName: '北京科技有限公司',
      customerRating: 'A+',
      contactPerson: '张三',
      contactPhone: '13800138001',
      paymentMonth: '2024-03',
      servicePeriod: '2024年1月-2024年12月',
      receivableAmount: 12000,
      memberEnterprise: '是',
      area: '北京',
      salesperson: '李四',
      accountant: '王五',
      followWechat: '已关注',
      receivedAmount: 8000,
      receivedUpTo: '2024-02',
      paymentStatus: '部分收款',
      lastPushTime: '2024-03-15 10:30:00',
      receiptNumber: 'SP2024001',
      assistant: '赵六',
      paymentRemark: '已收到部分款项8000元，剩余4000元客户承诺月底前支付',
    },
    {
      id: 2,
      customerCode: 'KH002',
      serviceProject: '财务咨询',
      customerName: '上海贸易有限公司',
      customerRating: 'A',
      contactPerson: '李明',
      contactPhone: '13900139002',
      paymentMonth: '2024-03',
      servicePeriod: '2024年1月-2024年6月',
      receivableAmount: 8000,
      memberEnterprise: '否',
      area: '上海',
      salesperson: '王七',
      accountant: '陈八',
      followWechat: '未关注',
      receivedAmount: 8000,
      receivedUpTo: '2024-03',
      paymentStatus: '已收齐',
      lastPushTime: '2024-03-10 14:20:00',
      receiptNumber: 'SP2024002',
      assistant: '刘九',
      paymentRemark: '款项已全部到账，通过银行转账方式，发票已寄送完成',
    },
    {
      id: 3,
      customerCode: 'KH003',
      serviceProject: '税务筹划',
      customerName: '深圳创新科技',
      customerRating: 'B+',
      contactPerson: '王华',
      contactPhone: '13700137003',
      paymentMonth: '2024-04',
      servicePeriod: '2024年1月-2024年12月',
      receivableAmount: 15000,
      memberEnterprise: '是',
      area: '深圳',
      salesperson: '张十',
      accountant: '李十一',
      followWechat: '已关注',
      receivedAmount: 0,
      receivedUpTo: '',
      paymentStatus: '未收款',
      lastPushTime: '2024-03-12 09:15:00',
      receiptNumber: '',
      assistant: '陈十二',
      paymentRemark: '客户要求提供详细费用清单，已发送，等待审核后付款',
    },
    {
      id: 4,
      customerCode: 'KH004',
      serviceProject: '审计服务',
      customerName: '广州制造有限公司',
      customerRating: 'A',
      contactPerson: '陈丽',
      contactPhone: '13600136004',
      paymentMonth: '2024-03',
      servicePeriod: '2024年1月-2024年12月',
      receivableAmount: 20000,
      memberEnterprise: '是',
      area: '广州',
      salesperson: '李四',
      accountant: '王五',
      followWechat: '已关注',
      receivedAmount: 15000,
      receivedUpTo: '2024-02',
      paymentStatus: '部分收款',
      lastPushTime: '2024-03-14 16:45:00',
      receiptNumber: 'SP2024003',
      assistant: '赵六',
      paymentRemark: '已收到15000元，剩余5000元客户申请下月一次性结清',
    },
    {
      id: 5,
      customerCode: 'KH005',
      serviceProject: '代理记账',
      customerName: '杭州电商科技',
      customerRating: 'B',
      contactPerson: '刘强',
      contactPhone: '13500135005',
      paymentMonth: '2024-04',
      servicePeriod: '2024年1月-2024年6月',
      receivableAmount: 6000,
      memberEnterprise: '否',
      area: '杭州',
      salesperson: '王七',
      accountant: '陈八',
      followWechat: '未关注',
      receivedAmount: 6000,
      receivedUpTo: '2024-04',
      paymentStatus: '已收齐',
      lastPushTime: '2024-03-13 11:20:00',
      receiptNumber: 'SP2024004',
      assistant: '刘九',
      paymentRemark: '客户通过微信转账6000元，已确认到账，服务满意度良好',
    },
    {
      id: 6,
      customerCode: 'KH006',
      serviceProject: '财务培训',
      customerName: '北京教育科技',
      customerRating: 'C',
      contactPerson: '张敏',
      contactPhone: '13400134006',
      paymentMonth: '2024-05',
      servicePeriod: '2024年3月-2024年8月',
      receivableAmount: 10000,
      memberEnterprise: '否',
      area: '北京',
      salesperson: '张十',
      accountant: '李十一',
      followWechat: '未关注',
      receivedAmount: 0,
      receivedUpTo: '',
      paymentStatus: '未收款',
      lastPushTime: '2024-03-11 08:30:00',
      receiptNumber: '',
      assistant: '陈十二',
      paymentRemark: '客户财务人员变更，新联系人正在办理付款手续',
    }
  ];

  // 计算合计数据
  const calculateSummary = (data) => {
    const totalCustomers = data.length;
    const totalReceivableAmount = data.reduce((sum, item) => {
      return sum + (item.receivableAmount || 0);
    }, 0);

    setSummaryData({
      totalCustomers,
      totalReceivableAmount,
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '客户名称',
      dataIndex: 'customerName',
      width: 150,
      fixed: 'left',
    },
    {
      title: '服务项目',
      dataIndex: 'serviceProject',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '客户编号',
      dataIndex: 'customerCode',
      width: 100,
      fixed: 'left',
    },
    {
      title: '客户评级',
      dataIndex: 'customerRating',
      width: 100,
      valueType: 'select',
      valueEnum: {
        'A+': { text: 'A+' },
        'A': { text: 'A' },
        'B+': { text: 'B+' },
        'B': { text: 'B' },
        'C': { text: 'C' },
      },
      render: (rating) => {
        const color = rating === 'A+' ? 'gold' : rating === 'A' ? 'green' : rating === 'B+' ? 'blue' : 'default';
        return <Tag color={color}>{rating}</Tag>;
      },
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
      width: 100,
    },
    {
      title: '联系人手机号',
      dataIndex: 'contactPhone',
      width: 130,
    },
    {
      title: '回款月份',
      dataIndex: 'paymentMonth',
      width: 100,
      valueType: 'dateMonth',
    },
    {
      title: '服务期间',
      dataIndex: 'servicePeriod',
      width: 200,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '应收服务费',
      dataIndex: 'receivableAmount',
      width: 120,
      hideInSearch: true,
      render: (amount) => `¥${amount?.toLocaleString()}`,
      sorter: true,
    },
    // 收款备注
    {
      title: '收款备注',
      dataIndex: 'paymentRemark',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '成员企业',
      dataIndex: 'memberEnterprise',
      width: 100,
      hideInSearch: true,
      render: (isMember) => (
        <Tag color={isMember === '是' ? 'success' : 'default'}>
          {isMember}
        </Tag>
      ),
    },
    {
      title: '区域',
      dataIndex: 'area',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '北京': { text: '北京' },
        '上海': { text: '上海' },
        '广州': { text: '广州' },
        '深圳': { text: '深圳' },
        '杭州': { text: '杭州' },
        '其他': { text: '其他' },
      },
    },
    {
      title: '接单人',
      dataIndex: 'salesperson',
      width: 100,
    },
    {
      title: '记账会计',
      dataIndex: 'accountant',
      width: 100,
    },
    {
      title: '关注公众号',
      dataIndex: 'followWechat',
      width: 120,
      valueType: 'select',
      valueEnum: {
        '已关注': { text: '已关注' },
        '未关注': { text: '未关注' },
      },
      render: (status) => (
        <Tag color={status === '已关注' ? 'success' : 'warning'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '已收金额',
      dataIndex: 'receivedAmount',
      width: 120,
      hideInSearch: true,
      render: (amount) => `¥${amount?.toLocaleString()}`,
      sorter: true,
    },
    {
      title: '已收费至',
      dataIndex: 'receivedUpTo',
      width: 100,
      hideInSearch: true,
      render: (month) => month || '-',
    },
    {
      title: '收款状态',
      dataIndex: 'paymentStatus',
      width: 100,
      valueType: 'select',
      valueEnum: {
        '已收齐': { text: '已收齐' },
        '部分收款': { text: '部分收款' },
        '未收款': { text: '未收款' },
      },
      render: (status) => {
        const color = status === '已收齐' ? 'success' : status === '部分收款' ? 'warning' : 'error';
        return <Tag color={color}>{status}</Tag>;
      },
    },
    {
      title: '上次推送时间',
      dataIndex: 'lastPushTime',
      width: 160,
      hideInSearch: true,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '收款单',
      dataIndex: 'receiptNumber',
      width: 120,
      hideInSearch: true,
      render: (number) => number || '-',
    },
    {
      title: '协助人',
      dataIndex: 'assistant',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 260,
      fixed: 'right',
      hideInSearch: true,
      render: (text, record) => (
        <Space>
          <Button size="small" onClick={() => handleCopy(record)}>复制账单</Button>
          <Button size="small" onClick={() => handleCollect(record)}>收款</Button>
          <Button size="small" onClick={() => handlePush(record)}>推送</Button>
          <Button size="small" onClick={() => handleAssist(record)}>协助</Button>
        </Space>
      ),
    },
  ];

  const handleCopy = (record) => {
    console.log(record);
    message.info(`复制账单 ( ${record.customerName} )`);
  };
  const handleCollect = (record) => {
    console.log(record);
    message.info(`收款 ( ${record.customerName} )`);
  };
  const handlePush = (record) => {  
    console.log(record);
    message.info(`推送 ( ${record.customerName} )`);
  };
  const handleAssist = (record) => {
    console.log(record);
    message.info(`协助 ( ${record.customerName} )`);
  };

  // 获取数据的函数
  const getContractPayments =  (params) => {
    let filteredData = [...mockData];

    // 只有有筛选条件时才过滤
    if (params) {
      if (params.customerCode) {
        filteredData = filteredData.filter(item => item.customerCode.includes(params.customerCode));
      }
      if (params.customerName) {
        filteredData = filteredData.filter(item => item.customerName.includes(params.customerName));
      }
      if (params.contactPerson) {
        filteredData = filteredData.filter(item => item.contactPerson.includes(params.contactPerson));
      }
      if (params.contactPhone) {
        filteredData = filteredData.filter(item => item.contactPhone.includes(params.contactPhone));
      }
      if (params.paymentMonth) {
        filteredData = filteredData.filter(item => item.paymentMonth === params.paymentMonth);
      }
      if (params.customerRating) {
        filteredData = filteredData.filter(item => item.customerRating === params.customerRating);
      }
      if (params.area) {
        filteredData = filteredData.filter(item => item.area === params.area);
      }
      if (params.salesperson) {
        filteredData = filteredData.filter(item => item.salesperson.includes(params.salesperson));
      }
      if (params.accountant) {
        filteredData = filteredData.filter(item => item.accountant.includes(params.accountant));
      }
      if (params.followWechat) {
        filteredData = filteredData.filter(item => item.followWechat === params.followWechat);
      }
      if (params.paymentStatus) {
        filteredData = filteredData.filter(item => item.paymentStatus === params.paymentStatus);
      }
    }

    // 分页
    const { current = 1, pageSize = 10 } = params || {};
    const start = (current - 1) * pageSize;
    const end = start + pageSize;
    const pagedData = filteredData.slice(start, end);

    calculateSummary(pagedData); // 计算合计数据

console.log(pagedData);

    return {
      data: pagedData,
      success: true,
      total: filteredData.length,
    };
  };

  return (
    <PageContainer
      header={{
        title: '合同收款',
        subTitle: '合同收款管理页面',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={getContractPayments}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        toolBarRender={() => [
          <div key="summary" style={{
            display: 'flex',
            alignItems: 'center',
            gap: '24px',
            fontSize: '14px',
            color: '#666'
          }}>
            <span>
              <UserOutlined style={{ marginRight: '4px', color: '#1890ff' }} />
              合计：<strong style={{ color: '#1890ff' }}>{summaryData.totalCustomers}</strong> 户
            </span>
            <span>
              <DollarOutlined style={{ marginRight: '4px', color: '#52c41a' }} />
              待收费合计：<strong style={{ color: '#52c41a' }}>¥{summaryData.totalReceivableAmount.toLocaleString()}</strong> 元
            </span>
          </div>
        ]}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
          filterType: 'light',
          placement: 'bottomLeft',
        }}
        scroll={{ x: 2000 }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        dateFormatter="string"
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        tableAlertOptionRender={({selectedRowKeys, selectedRows}) => {
          return (
            <Button type="primary" size="small" onClick={() => {
              message.info(`批量推送 ( ${selectedRowKeys.length} )`);
            }}>
              批量推送 ( {selectedRowKeys.length} )
            </Button>
          );
        }}
      />
    </PageContainer>
  );
};

export default ContractPayment; 